import { Component } from 'react'
import { connect } from 'react-redux'
import Taro from '@tarojs/taro'
import {
  View,
  Text,
  Button,
  ScrollView,
  Swiper,
  SwiperItem,
  Image,
  RichText,
} from '@tarojs/components'
import { AtNavBar, AtFloatLayout, AtInputNumber, AtTag } from 'taro-ui'
import classNames from 'classnames'

import * as api from 'src/api'
import { setPid } from 'src/store/slice/user'
import { getToken } from 'src/utils/app'

import './index.scss'

type PageStateProps = {
  userInfo: { [key: string]: any }
}

type PageDispatchProps = {
  setPid: (pid) => void
}

type PageOwnProps = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

type IState = {
  storeInfo: { [key: string]: any }
  sliderImage: any[]
  productAttr: any[]
  attribute: {
    stock: number
    cartNum: number
    [key: string]: any
  }
  showAttribute: boolean
  opacity: number
  statusBarHeight: number
  windowHeight: number
}

interface Index {
  props: IProps
  state: IState
  id: string
  productValue: {
    [key: string]: any
  }
  isLogin: boolean
}

const connectRedux: Function = connect

@connectRedux(
  ({ user }) => ({
    userInfo: user.userInfo,
  }),
  (dispatch) => ({
    setPid(pid) {
      dispatch(setPid(pid))
    },
  })
)
class Index extends Component {
  state: IState = {
    storeInfo: {},
    sliderImage: [],
    productAttr: [],
    attribute: {
      stock: 1,
      cartNum: 1,
    },
    showAttribute: false,
    opacity: 0,
    statusBarHeight: 0,
    windowHeight: 0,
  }

  componentWillMount() {
    this.isLogin = !!getToken()
  }

  async componentDidMount() {
    const res = await Taro.getSystemInfo()
    // 胶囊 top:4+height32+bottom:8=44
    this.setState({
      statusBarHeight: res.statusBarHeight,
      windowHeight: res.windowHeight,
    })
  }

  async onLoad(options) {
    if (!options.id) {
      Taro.showToast({ title: '缺少参数无法查看商品', icon: 'none' })
    } else {
      this.id = options.id
      this.getProductDetail()
    }
  }

  onShareAppMessage() {
    return {
      title: this.state.storeInfo.storeName,
      path: `/pages/product_detail/index?id=${this.id}&pid=${this.props.userInfo.uid}`,
      imageUrl: this.state.storeInfo.image,
    }
  }

  getProductDetail = async () => {
    Taro.showLoading({ title: '加载商品中' })
    const res = await api.getProductDetail(this.id)
    this.productValue = res.productValue
    Taro.hideLoading()
    this.setState({
      storeInfo: res.storeInfo,
      sliderImage: JSON.parse(res.storeInfo.sliderImage),
      productAttr: res.productAttr,
    })
    this.defaultSelect()
  }

  defaultSelect = () => {
    let attribute = {}
    let value: string[] = []
    const { storeInfo, productAttr } = this.state
    for (let key in this.productValue) {
      if (this.productValue[key].stock > 0) {
        value = productAttr.length ? key.split(',') : []
        break
      }
    }
    for (let i = 0; i < productAttr.length; i++) {
      productAttr[i]['index'] = value[i]
    }

    let productSelect = this.productValue[value.join(',')]
    if (productSelect && productAttr.length) {
      attribute = {
        storeName: storeInfo.storeName,
        index: value.join(','),
        image: productSelect.image,
        price: productSelect.price,
        stock: productSelect.stock,
        unique: productSelect.id,
        cartNum: 1,
      }
    } else if (!productSelect && productAttr.length) {
      attribute = {
        storeName: storeInfo.storeName,
        index: '',
        image: storeInfo.image,
        price: storeInfo.price,
        stock: 0,
        unique: storeInfo.id,
        cartNum: 1,
      }
    } else if (!productSelect && !productAttr.length) {
      attribute = {
        storeName: storeInfo.storeName,
        index: '',
        image: storeInfo.image,
        price: storeInfo.price,
        stock: storeInfo.stock,
        unique: storeInfo.id,
        cartNum: 1,
      }
    }
    this.setState({ productAttr, attribute })
  }

  handleChangeAttr = (i, j) => {
    let attribute = {}
    let value: string[] = []
    const { storeInfo, productAttr } = this.state
    console.log(productAttr)

    productAttr[i]['index'] = productAttr[i].attrValues[j]
    for (let m = 0; m < productAttr.length; m++) {
      for (let n = 0; n < productAttr[m].attrValues.length; n++) {
        if (productAttr[m].index === productAttr[m].attrValues[n]) {
          value.push(productAttr[m].index)
        }
      }
    }
    let productSelect = this.productValue[value.join(',')]
    attribute = {
      storeName: storeInfo.storeName,
      index: value.join(','),
      image: productSelect.image,
      price: productSelect.price,
      stock: productSelect.stock,
      unique: productSelect.id,
      cartNum: 1,
    }
    this.setState({ productAttr, attribute })
  }

  handleBuy = async () => {
    const { storeInfo, attribute } = this.state
    if (!attribute.index) {
      this.handleShowAttribute()
      return
    }
    try {
      const res = await api.addCart({
        productId: Number(this.id),
        cartNum: Number(attribute.cartNum),
        isNew: true,
        productAttrUnique: attribute.unique || storeInfo.id,
      })
      Taro.navigateTo({
        url: `/pages/order_confirm/index?new=true&cartId=${res.cartId}`,
      })
    } catch (error) {
      Taro.showToast({ title: '系统错误', icon: 'none' })
    }
  }

  goBack = () => {
    if (Taro.getCurrentPages().length > 1) {
      Taro.navigateBack()
    } else {
      Taro.navigateTo({
        url: '/pages/index/index',
      })
    }
  }

  handleScroll = (e) => {
    const scrollTop = e.detail.scrollTop
    let opacity = scrollTop / 200
    if (opacity > 1) {
      opacity = 1
    }
    this.setState({ opacity })
  }

  handleShowAttribute = () => {
    this.setState({ showAttribute: !this.state.showAttribute })
  }

  handleChangeCartNum = (value: number) => {
    const { attribute } = this.state
    this.setState({ attribute: { ...attribute, cartNum: value } })
  }

  handleBlurCartNum = (event: any) => {
    if (event.detail.value == 0) {
      const { attribute } = this.state
      this.setState({ attribute: { ...attribute, cartNum: 1 } })
    }
  }

  render() {
    const {
      storeInfo,
      sliderImage,
      productAttr,
      attribute,
      showAttribute,
      opacity,
      statusBarHeight,
      windowHeight,
    } = this.state
    return (
      <View className="product-detail">
        <View
          className="navbar"
          style={{
            backgroundColor: `rgba(255,255,255,${opacity})`,
          }}
        >
          <View style={{ height: statusBarHeight }}></View>
          <AtNavBar
            color="#000"
            title={storeInfo.storeName?.substring(0, 7) + '...'}
            leftIconType="chevron-left"
            onClickLeftIcon={this.goBack}
          />
        </View>
        <ScrollView
          className="scrollview"
          style={{ height: windowHeight }}
          scrollY
          onScroll={this.handleScroll}
        >
          <Swiper
            className="product-images"
            indicatorActiveColor="#e93323"
            indicatorDots
            circular
            autoplay
          >
            {sliderImage.map((item, index) => (
              <SwiperItem key={index}>
                <Image src={item}></Image>
              </SwiperItem>
            ))}
          </Swiper>
          <View className="store-base-info card">
            <View className="money at-row at-row__justify--between at-row__align--center">
              <View className="price price-color">
                ￥<Text>{storeInfo.price}</Text>
              </View>
              <Button className="share remove-button-style" open-type="share">
                <View className="at-icon at-icon-share"></View>
              </Button>
            </View>
            <View className="name">{storeInfo.storeName}</View>
            <View className="label at-row at-row__justify--between">
              <View>原价:￥{storeInfo.otPrice || 0}</View>
              <View>
                库存:{storeInfo.stock || 0}
                {storeInfo.unitName || ''}
              </View>
              <View>
                销量:
                {Math.floor(storeInfo.sales) + Math.floor(storeInfo.ficti) || 0}
                {storeInfo.unitName || ''}
              </View>
            </View>
          </View>
          <View className="card" onClick={this.handleShowAttribute}>
            <View className="attribute at-row at-row__justify--between at-row__align--center">
              <View>
                {attribute.index ? '已选择' : '请选择'}：
                <Text className="attr-txt">{attribute.index}</Text>
              </View>
              <View className="arrow at-icon at-icon-chevron-right"></View>
            </View>
          </View>
          <View className="description">
            <View className="title">产品介绍</View>
            <RichText
              className="conter"
              nodes={storeInfo?.content?.replace(
                /<img/gi,
                '<img style="display:block;max-width:100%;height:auto;" '
              )}
            />
          </View>
          <View style={{ height: 50 }}></View>
        </ScrollView>
        <View className="footer at-row at-row__justify--between at-row__align--center">
          <Button
            className="kefu remove-button-style"
            open-type="contact"
            hoverClass="none"
          >
            <View className="user at-icon at-icon-user"></View>
            <View>客服</View>
          </Button>
          <Button
            className={classNames('buy', { disabled: attribute.stock <= 0 })}
            disabled={attribute.stock <= 0}
            onClick={this.handleBuy}
          >
            {attribute.stock <= 0 ? '已售罄' : '立即购买'}
          </Button>
        </View>
        <AtFloatLayout
          className="attr-box"
          isOpened={showAttribute}
          onClose={this.handleShowAttribute}
        >
          <View className="at-row at-row__justify--between">
            <Image className="store-img" src={attribute.image}></Image>
            <View className="info at-col">
              <View className="title line1">{attribute.storeName}</View>
              <View className="money price-color">
                ￥<text className="num">{attribute.price}</text>
                <text className="stock">库存: {attribute.stock}</text>
              </View>
            </View>
            <View
              className="close at-icon at-icon-close"
              onClick={this.handleShowAttribute}
            ></View>
          </View>
          {productAttr.map((item, i) => (
            <View className="attr" key={i}>
              <View className="title">{item.attrName}</View>
              <View className="attr-list at-row">
                {item.attrValue.map(({ attr }, j) => (
                  <AtTag
                    key={j}
                    size="small"
                    circle
                    active={item.index === attr}
                    onClick={() => this.handleChangeAttr(i, j)}
                  >
                    {attr}
                  </AtTag>
                ))}
              </View>
            </View>
          ))}
          <View className="attr at-row at-row__justify--between at-row__align--center">
            <View className="title">数量</View>
            <AtInputNumber
              type="number"
              min={0}
              max={9999}
              step={1}
              value={attribute.cartNum}
              onChange={this.handleChangeCartNum}
              onBlur={this.handleBlurCartNum}
            />
          </View>
        </AtFloatLayout>
      </View>
    )
  }
}

export default Index
